# -*- coding: utf-8 -*-
# @时间：2023/11/2 20:16
# @作者：CJiaの可乐哥
# @文件名：middleware
# @软件：Pycharm2023
import time
import json

from system.models import Users, OperationLog, ErrorLog
from django.utils.deprecation import MiddlewareMixin

from utils.request_util import (
    get_os,
    get_browser,
    get_request_ip,
    get_request_path,
    get_request_data,
    get_request_user,
)


class ApiLoggingMiddleware(MiddlewareMixin):
    """
    用于记录API访问日志中间件
    """

    @classmethod
    def __handle_request(cls, request):
        request.start_time = time.time()
        request.request_ip = get_request_ip(request)
        request.request_path = get_request_path(request)
        request.request_data = get_request_data(request)

    def __handle_response(self, request, response):
        request_time = int((time.time() - request.start_time) * 1000)
        # request_data,request_ip由PermissionInterfaceMiddleware中间件中添加的属性
        body = getattr(request, 'request_data', {})
        # 请求含有password则用*替换掉(暂时先用于所有接口的password请求参数)
        if isinstance(body, dict) and body.get('password', ''):
            body['password'] = '*' * len(body['password'])
        if not hasattr(response, 'data') or not isinstance(response.data, dict):
            response.data = {}
        try:
            if not response.data and response.content:
                content = json.loads(response.content.decode())
                response.data = content if isinstance(content, dict) else {}
        except Exception:
            return
        user = get_request_user(request)
        info = {
            'request_time': request_time,
            'request_ip': getattr(request, 'request_ip', 'unknown'),
            'request_username': user.username if isinstance(user, Users) else user['username'],
            'request_path': request.request_path,
            'request_body': body,
            'request_method': request.method,
            'request_msg': request.session.get('request_msg'),
            'response_code': response.data.get('code'),
            'request_os': get_os(request),
            'request_browser': get_browser(request),
            'status': True if response.data.get('code') in [200, ] else False,
            'json_result': {"code": response.data.get('code'), "result": response.data.get('result'),
                            "msg": response.data.get('message')},
            'address': '',
        }
        if response.data.get('code') == 500:
            error = info
            error['result'] = response.data.get('message')
            ErrorLog.objects.create(**info)  # 保存异常
            return
        if request.method == "GET":
            return
        OperationLog.objects.create(**info)  # 保存操作

    def process_request(self, request):
        self.__handle_request(request)

    def process_response(self, request, response):
        self.__handle_response(request, response)
        # 返回结果
        return response
